package com.kcs.fxmargin.action;

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.kcs.common.utils.Constant;
import com.kcs.fxmargin.action.form.ConfigSystemActionForm;
import com.kcs.fxmargin.model.CConfigSys;
import com.kcs.fxmargin.service.CommonService;
import com.kcs.fxmargin.servlet.ContextListener;

public class ConfigSystemAction extends FXAction {
	private Logger log = Logger.getLogger(Constant.LOG_FX);
	
	CommonService service = new CommonService();

	@Override
	public ActionForward process(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// TODO Auto-generated method stub
		
		System.out.println("ConfigSystemAction : Start");
		
		try{
			
			ConfigSystemActionForm formBean = (ConfigSystemActionForm) form;
			
			if("init".equals(formBean.getAction())) {
				formBean.resetExpect();
				formBean.setConfigList(service.getConfig());				
			} else if ("save".equals(formBean.getAction())){
				int index = 0;
				for( CConfigSys config : formBean.getConfigList()){
					String[] configs = formBean.getConfigs();
					
					if(configs != null && configs.length > 0 ) {					
						System.out.println("Keys[" + config.getKeys() + "] = " + configs[index]);
						config.setValue(configs[index]);
						config.setUpdateBy(formBean.getUserLoginId());
						config.setRowVersion(config.getRowVersion() + 1);
						index++;
					}
				}
				
				service.updateConfig(formBean.getConfigList());
				
				ContextListener.properties = new HashMap<String, String>();
				
				for( CConfigSys config : formBean.getConfigList()){
					ContextListener.properties.put(config.getKeys(), config.getValue());
				}
				
				formBean.setAction("init");
			}
			
		} catch (Exception e){
			log.error(e);
			e.printStackTrace();
		}
		
		System.out.println("ConfigSystemAction : End");
		
		return mapping.findForward("configSystem");
	}


}
